﻿using ClearCanvas.Dicom;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ClearCanvas.Dicom.Example
{
    class Program
    {
        static void Main(string[] args)
        {
            DicomFile dicomFile = new DicomFile("D:\\work\\MedImages\\CR\\1.dcm");

            dicomFile.Load(DicomReadOptions.Default);

            var tagData = ReadAttributeCollection(dicomFile.MetaInfo, null, 0)
                .Concat(ReadAttributeCollection(dicomFile.DataSet, null, 0));

            System.Diagnostics.Debug.WriteLine(tagData.Count());

            var studyIUID = tagData.FirstOrDefault(o => o.Group == 0x0020 && o.Element == 0x000d);
            System.Diagnostics.Debug.WriteLine(studyIUID.TagName + "=" + studyIUID.Value);

            foreach (DicomEditorTag tag in tagData)
            {
                System.Diagnostics.Debug.WriteLine(
                    tag.TagId + "," + tag.DisplayKey
                    + "\t" + tag.Value + "\t" + tag.TagName);
            }
        }

        private static IEnumerable<DicomEditorTag> ReadAttributeCollection(DicomAttributeCollection set, DicomEditorTag parent, int nestingLevel)
        {
            foreach (DicomAttribute attribute in set)
            {
                if (attribute.IsEmpty)
                    continue;

                if (attribute is DicomAttributeSQ)
                {
                    DicomEditorTag editorSq = new DicomEditorTag(attribute, parent, nestingLevel);
                    yield return editorSq;

                    DicomSequenceItem[] items = (DicomSequenceItem[])attribute.Values;
                    if (items.Length != 0)
                    {
                        for (int i = 0; i < items.Length; i++)
                        {
                            var sequenceItem = items[i];

                            var editorSqItem = new DicomEditorTag("fffe", "e000", "Sequence Item", editorSq, i, nestingLevel + 1);
                            yield return editorSqItem;

                            foreach (var tag in ReadAttributeCollection(sequenceItem, editorSqItem, nestingLevel + 2))
                                yield return tag;

                            //add SQ Item delimiter
                            yield return new DicomEditorTag("fffe", "e00d", "Item Delimitation Item", editorSqItem, i, nestingLevel + 1);
                        }
                    }

                    //add SQ delimiter
                    yield return new DicomEditorTag("fffe", "e0dd", "Sequence Delimitation Item", editorSq, items.Length, nestingLevel);
                }
                else
                {
                    yield return new DicomEditorTag(attribute, parent, nestingLevel);
                }
            }
        }
    }
}
